﻿using Microsoft.Extensions.DependencyInjection;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Server;
using QModels;
using QServices.Services;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace QServices.QJobs;

/// <summary>
/// 每天2点定时充电
/// </summary>
public class CarElectricJob : IJob
{
	public Task Execute(IJobExecutionContext context)
	{

		AppRuntime.GetPlcManager().StartCarElectric();

		return Task.CompletedTask;
	}
}


public class SecondJob : IJob
{
	public Task Execute(IJobExecutionContext context)
	{


		return Task.CompletedTask;
	}
}

public class MinuteJob : IJob
{
	public async Task Execute(IJobExecutionContext context)
	{

		#region 检查当前网络是否正常,正常则更新任务列表
		if (AppRuntime.IsNetworkAvailable())
		{
			await AppRuntime.GetService().GetService<AgvCarService>().ChangeMqttCacheFromRemote();
		}


		#endregion
		#region 当电量小于指定电量时充电，当电量大于指定电量时关闭充电
		if (AppRuntime.AgvCar != null)
		{
			_ = Task.Run(() =>
			{
				try
				{
					var currentEleQty = AppRuntime.GetPlcManager().当前电量();
					if (currentEleQty > AppRuntime.AgvCar.MaxElectricQty)
					{
						AppRuntime.GetPlcManager().EndCarElectric();
					}
					else if (currentEleQty < AppRuntime.AgvCar.MinAllowEleQty)
					{
						AppRuntime.GetPlcManager().StartCarElectric();
					}
				}
				catch (Exception ex)
				{
					AppRuntime.Logger_Error(ex);
				}

			});
			

		}
		#endregion


	


	}
}

public class MinuteFiveJob : IJob
{
	public Task Execute(IJobExecutionContext context)
	{

		#region 检查当前网络是否正常,正常则同步数据
		if (AppRuntime.IsNetworkAvailable())
		{
			AppRuntime.GetService().GetService<AgvCarService>().UpdateAGVCarStatusModelToRemote();
        }


        #endregion

        return Task.CompletedTask;
	}
}

public class MinuteTenJob : IJob
{
	public Task Execute(IJobExecutionContext context)
	{


		return Task.CompletedTask;
	}
}

public class Second30Job : IJob
{
	public async Task Execute(IJobExecutionContext context)
	{

		if (AppRuntime.IsNetworkAvailable())
		{
			try
			{
				var eleQty = AppRuntime.GetPlcManager().当前电量();
				var tt = AppRuntime.GetPlcManager().GetGVCarStatusModel();

				var carstatus = tt.ChongDian ? CarStatus.Charging : CarStatus.None;
				carstatus = tt.GuZhangQuanBu ? CarStatus.Trouble : carstatus;
				carstatus = tt.WeiLiaoZhong ? CarStatus.WeiLiao : carstatus;
				var obj = new { CarNumber = AppRuntime.CarNumber, Qty = eleQty, TongXin = tt.TongXinOK, CarStatus = (int)carstatus };
				var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj));
				//RabbitMQChannel.ExchangeDeclare(exchange: "CarElectricQty", type: ExchangeType.Fanout, durable: true);
				var message = new MqttApplicationMessage
				{
					PayloadSegment = bytes,
					Topic = "CarElectricQty",
					QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce
				};

				if (!AppRuntime.m_mqttclient.IsConnected) await AppRuntime.m_mqttclient.ReconnectAsync();
				await AppRuntime.m_mqttclient.PublishAsync(message);

			}
			catch (Exception ex)
			{
				AppRuntime.Logger_Error("mqtt连接异常");
			}

		}
	}
}

public class ZeroJob : IJob
{
	public Task Execute(IJobExecutionContext context)
	{
		AppRuntime.GetService().GetService<AgvCarService>().DeleteAGVCarStatusModelLocal();
		return Task.CompletedTask;
	}
}


